package cn.tristenstudy.handle;

import cn.tristenstudy.util.EmailUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import java.io.IOException;

/**
 * 通过rabbitMQ发送邮件
 *
 * @author xichen1.li
 * @date 2021-01-26 11:51
 */
@Component
public class RabbitMQListener {

    @Autowired
    private EmailUtil emailUtil;
    @Value("${file.url}")
    private String fileUrl;

    @RabbitListener(queues = "email_queue")
    public void getDirectMessage(Channel channel, Message message) throws IOException {
        String messageStr = new String(message.getBody());
        //当前消息的标签
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        if (StringUtils.hasLength(messageStr)) {
            try {
                String email = messageStr.split(":")[0];
                String nickname = messageStr.split(":")[1];
                String encoding = "utf-8";
                String subject = "STM32仿真课件";
                String text = "<h3>Dear <span style=\"color: #00aaaa\">" + nickname + "</span>:</h3><p style=\"text-indent: 30px;font-size: 15px\">感谢你的支持，请查收STM32课件~</p>";
                String path = fileUrl;
                String fileName = "STM32仿真课设.zip";
                String sendFrom = "2519294308@qq.com";
                try {
                    emailUtil.sendMail(true, encoding, subject, text, path, fileName, email, sendFrom);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                channel.basicAck(deliveryTag,true);
            }catch (Exception e){
                //第三个参数：是否重回队列（消息重新回到queue中，broker会重新发送消息）
                channel.basicNack(deliveryTag,true,true);
            }
        }
    }
}
